package com.dgut.healthreportmanage.controller;

import com.dgut.healthreportmanage.pojo.Report;
import com.dgut.healthreportmanage.pojo.User;
import com.dgut.healthreportmanage.service.ReportService;
import com.dgut.healthreportmanage.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Controller
public class ReportController {
    @Autowired
    private ReportService reportService;

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/getReport")
    public ModelAndView getReport(HttpSession httpSession) throws java.text.ParseException {
        User user = (User) httpSession.getAttribute("user");
        ModelAndView modelAndView = new ModelAndView();
        //获取最新上报记录
        Report report= reportService.getLatestReportByUserId(user.getUserId());
        httpSession.setAttribute("report", report);
        //判断当日是否已上报
        String message = "您今日已上报";
        Date date = new Date();
        if (report.getDate() == null ||
                !(report.getDate().toString().equals(new java.sql.Date(date.getTime()).toString()))) {
            message = "您今日未上报";
            report.setDate(new java.sql.Date(date.getTime()));
        }
        modelAndView.addObject("message", message);
        modelAndView.setViewName("index");
        return modelAndView;
    }

    @RequestMapping(value = "/report")
    public String report(Report report, HttpSession httpSession){
        User user = (User) httpSession.getAttribute("user");
        reportService.addReport(user,report);
        user = userService.getUserByUserNo(user.getUserNo());
        httpSession.setAttribute("user", user);
        return "redirect:/getReport";
    }
}
